package middleware

import (
	"fmt"
	"net/http"

	"gddgame.cc/galaxy/utils/cache"
	"gddgame.cc/galaxy/utils/def"
	"gddgame.cc/galaxy/utils/uuid"
)

//cookie := &http.Cookie{
//	Path:     "/",
//	HttpOnly: true,
//	Secure:   false,
//	MaxAge:   30 * 24 * 60 * 60 * 1000, //30 day in ms
//}
//router.Use(middleware.SessionWrap("gak", builder.Store("admin"), cookie))

func SessionWrap(logger def.Logger, key string, store def.Store, cookie *http.Cookie) Handler {
	cc := cache.Memory(logger)
	return func(context Context, next Next) error {
		ck, err := context.Cookie(cookie.Name)

		var sid string
		var sok bool
		if err != nil {
			sid = uuid.RandomString()
			sok = false
		} else {
			sid = ck.Value
			sok = true
		}
		s := cc.Store(sid)
		defer cc.Clean(sid)
		if sok {
			// session存储失效
			if err := store.Get(key+"/"+ck.Value, &s.Data); err != nil {
				fmt.Println("middle session", err)
			}
		}
		context.SetStore(s)
		// 设定log标识
		context.SetLogger(context.LoggerWrap("sessionId", sid))
		context.SetID(sid)

		if err := next(nil); err != nil {
			fmt.Println("session middle", err)
			return err
		}
		ck = &http.Cookie{
			Name:     cookie.Name,
			Path:     cookie.Path,
			HttpOnly: cookie.HttpOnly,
			Secure:   cookie.Secure,
			Value:    sid,
			MaxAge:   cookie.MaxAge,
		}
		http.SetCookie(context.Writer(), ck)
		//fmt.Println(sid)
		//fmt.Println(s.Data)
		return store.Set(key+"/"+ck.Value, s.Data)
	}
}
